from manage_mysql import todo
from flask import Flask,request

app=Flask(__name__)
app.config['JSON_AS_ASCTT']=False
manage=todo()
manage.get_list()
#创建一个接口来获取请求，返回响应内容
@app.route('/') #当路由获取地址为跟路径的话，执行下面的函数
def hello_word():
    return "<p>Hello,Word!</p>"

@app.route('/todos',methods=['GET'])
def list_todos():
    if request.args['completed']=='all':
        return {'todos': [x.__dict__ for x in manage.get_list()]}
    elif request.args['completed']=='1':
        return {'todos': [x.__dict__ for x in manage.get_list() if x.completed]}
    elif request.args['completed']=='0':
        return {'todos': [x.__dict__ for x in manage.get_list() if not x.completed]}

@app.route("/todos",methods=['POST'])
def creat_todo():
    if 'title' not in request.form:
        return '参数错误，必须提供 title参数',400
    todo=manage.create(request.form['title'])
    return todo.__dict__
@app.route("/todos/mark_completed",methods=['GET'])
def mark_completeds():
    if 'id' not in request.args:
        return '参数错误，必须提供id参数',400
    todo_id=int(request.args['id'])
    todo=manage.mark_completed(todo_id)
    if todo is not None:
        return todo.__dict__
    else:
        return f'todo not found,id={todo_id}',404
@app.route("/todos/del_todo",methods=['GET'])
def del_todo():
    if 'title' not in request.args:
        return '参数错误，必须提供title参数',400
    todo_title=request.args['title']
    todo=manage.del_todo(todo_title)
    if todo is not None:
        return todo.__dict__

    else:
        return f'todo not found,todo_title={todo_title}', 404


if __name__=="__main__":  #让程序运行
    app.run()
